package cn.hanyx.coder.core.concurrent.rw;

/**
 * @author CSS
 */
public class ThreadSafeSample {
    public int sharedState;
//    ReentrantLock reentrantLock = new ReentrantLock(true);

    public void nonSafeAction() {
        synchronized (this) {
            subNonSafeAction();
        }
//        reentrantLock.lock();
//        try {
//            subNonSafeAction();
//        }finally {
//            reentrantLock.unlock();
//        }
    }

    private void subNonSafeAction() {
        while (sharedState < 100000) {
            int former = sharedState++;
            int latter = sharedState;
            if (former != latter - 1) {
                System.out.printf("Observed data race, former is " +
                        former + ", " + "latter is " + latter);
            }
        }
    }

    public static void main(String[] args) throws Exception {
        ThreadSafeSample sample = new ThreadSafeSample();
        Thread threadA = new Thread(() -> sample.nonSafeAction());
        Thread threadB = new Thread(() -> sample.nonSafeAction());
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
    }
}